package com.company.common.config;

import com.company.user.entity.UserEntity;
import org.springframework.util.Assert;

/**
 * 统一用户对象threadlocal类，每个线程绑定一个登录用户，注意该类禁止被继承统一用户对象threadlocal类，每个线程绑定一个登录用户，注意该类禁止被继承
 *
 * @author lincq
 * @date 2019/9/26 18:36
 */
public final class ThreadCachePool {


    private static ThreadLocal<UserEntity> cacheUser = new ThreadLocal<>();

    /**
     * 设置登录用户
     */
    public static void setUserInfo(UserEntity user) {
        cacheUser.set(user);
    }

    public static UserEntity getUserInfo(Boolean nullable) {
        UserEntity localUser = cacheUser.get();
        if (!nullable) {
            Assert.notNull(localUser, "获取当前登录用户信息失败");
        }
        return localUser;
    }

    public static void removeUserInfo() {
        cacheUser.remove();
    }

    public static String getUserId() {
        return getUserId(false);
    }

    public static String getUserId(Boolean returnNull) {
        UserEntity localUser = getUserInfo(returnNull);
        String userId;
        if (returnNull) {
            userId = null == localUser ? null : localUser.getUserId();
        }
        else {
            Assert.notNull(localUser, "获取当前登录用户信息失败");
            userId = localUser.getUserId();
        }
        return userId;
    }

}
